package top.onedream.buildsmallsoftware.util

import top.onedream.buildsmallsoftware.cfg.exception.CustomException
import top.onedream.buildsmallsoftware.enums.ExceptionEnum
import top.onedream.buildsmallsoftware.model.user.User


/**
 * 令牌持有人
 * @author zhangkein
 * @date 2023/05/16
 */
object TokenHolder {
    private val tokenHolder = ThreadLocal<User>()
    var user: User
        get() {
            if (tokenHolder.get() == null) {
                throw CustomException(ExceptionEnum.UN_LOGIN)
            }
            return tokenHolder.get()
        }
        private set(user) {
            tokenHolder.set(user)
        }

    fun removeToken() {
        tokenHolder.remove()
    }

    fun setTokenFromRequest(user: User?) {
        if (user != null) {
            TokenHolder.user = user
        } else {
            throw CustomException(ExceptionEnum.UN_LOGIN)
        }
    }
}

